package com.hunan.api.catv.service.biz.activity;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.hunan.api.catv.common.CacheKey;
import com.hunan.api.catv.common.CacheName;
import com.hunan.api.catv.common.Constants;
import com.hunan.api.catv.common.ConstantsMsg;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.enums.State;
import com.hunan.api.catv.entity.po.Activity;
import com.hunan.api.catv.entity.po.ActivityNews;
import com.hunan.api.catv.entity.po.News;
import com.hunan.api.catv.entity.vo.ActivityVo;
import com.hunan.api.catv.entity.vo.MemberVo;
import com.hunan.api.catv.entity.vo.NewsVo;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.cache.CacheBiz;
import com.hunan.api.catv.service.biz.member.MemberBiz;
import com.hunan.api.catv.service.biz.mq.MqBiz;
import com.hunan.api.catv.service.impl.activity.ActivityService;
import com.hunan.api.catv.service.impl.news.NewsService;
import com.hunan.api.catv.utils.RedisUtils;
import com.hunan.api.catv.utils.ThreeDesUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.net.URLEncoder;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

@Service
@CacheConfig(cacheNames = CacheName.activity)
public class ActivityBiz extends ResultService {

    @Autowired
    ActivityService activityService;

    @Autowired
    ActivityBiz activityBiz;

    @Autowired
    CacheBiz cacheBiz;

    @Autowired
    MqBiz mqBiz;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    MemberBiz memberBiz;

    @Autowired
    ActivityVideoBiz activityVideoBiz;

    @Autowired
    NewsService newsService;


    public ServiceResult add(Activity activity) {
        ServiceResult addResult = activityService.add(activity);
        if (addResult.getStatus()) {
            return addResult;
        }
        return buildFail(ConstantsMsg.admin_add_fail);
    }

    public ServiceResult edit(Activity activity) {
        ServiceResult serviceResult = activityService.update(activity);
        if (serviceResult.getStatus()) {
            String simpleInfoKey = MessageFormat.format(CacheName.activityInfo, String.valueOf(activity.getActivityId()));
            cacheBiz.flushCacheInfo("activityInfoCache?" + activity.getActivityId(), simpleInfoKey);
            return serviceResult;
        }
        return buildFail(ConstantsMsg.admin_edit_fail);
    }

    public ServiceResult edit(Integer activityId, Integer state) {
        Activity activity = new Activity();
        activity.setActivityId(activityId);
        activity.setState(state);
        ServiceResult serviceResult = activityService.update(activity);
        if (serviceResult.getStatus()) {
            String simpleInfoKey = MessageFormat.format(CacheName.activityInfo, String.valueOf(activityId));
            cacheBiz.flushCacheInfo("activityInfoCache?" + activityId, simpleInfoKey);
        }
        return serviceResult;
    }

    public ServiceResult editTop(Integer activityId, Integer isTop) {
        Activity activity = new Activity();
        activity.setActivityId(activityId);
        activity.setIsTop(isTop);
        ServiceResult serviceResult = activityService.update(activity);
        if (serviceResult.getStatus()) {
            String simpleInfoKey = MessageFormat.format(CacheName.activityInfo, String.valueOf(activityId));
            cacheBiz.flushCacheInfo("activityInfoCache?" + activityId, simpleInfoKey);
        }
        return serviceResult;
    }

    public ActivityVo getById(Integer activityId) {
        return activityService.getById(activityId);
    }

    public PageInfo<ActivityVo> adminList(Integer state, Integer activityId, int pageNum, int pageSize, Integer isTop, String title) {
        PageHelper.startPage(pageNum, pageSize);
        Activity activity = new Activity();
        activity.setActivityId(activityId);
        activity.setState(state);
        activity.setIsTop(isTop);
        activity.setTitle(title);
        List<ActivityVo> list = activityService.list(activity);
        for (int i = 0; i < list.size(); i++) {
            ActivityVo activityVo = list.get(i);
            State stateEnum = State.getResult(activityVo.getState());
            activityVo.setStateMsg(stateEnum.getMsg());
        }
        return new PageInfo<>(list);
    }

    public ActivityVo simpleReplaceCache(Integer activityId) {
        return activityService.simpleInfo(activityId);
    }

    //@Cacheable(unless = "#result == null")
    public PageInfo<ActivityVo> page(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Activity activity = new Activity();
        activity.setState(1);
        List<ActivityVo> listVo = new LinkedList<ActivityVo>();
        PageInfo<Integer> idsPage = activityBiz.idsList(pageNum, pageSize);
        List<Integer> idsList = idsPage.getList();
        for (Integer id : idsList) {
            ActivityVo activityVo = activityBiz.info(id);
            if (!ObjectUtils.isEmpty(activityVo)) {
                listVo.add(activityVo);
            }
        }
        PageInfo<ActivityVo> pageInfo = new PageInfo<ActivityVo>();
        BeanUtils.copyProperties(idsPage, pageInfo);
        pageInfo.setList(listVo);
        return pageInfo;
    }

    @Cacheable(unless = "#result == null")
    public PageInfo<Integer> idsList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Activity activity = new Activity();
        activity.setState(1);
        List<Integer> list = activityService.listIds(activity);
        return new PageInfo<>(list);
    }

    @Cacheable(unless = "#result == null")
    public ActivityVo simpleInfo(Integer activityId) {
        return activityService.simpleInfo(activityId);
    }

    @Cacheable(unless = "#result == null")
    public ActivityVo info(Integer activityId) {
        ActivityVo activityVo = activityService.getById(activityId);
        if (!ObjectUtils.isEmpty(activityVo)) {
            String shareLinkdomain = cacheBiz.getSystemDict(Constants.shareLink_domain);
            activityVo.setShareLink(shareLinkdomain + "/h5/activity?activityId=" + activityId);
//    		List<ActivityVideoVo> list = activityVideoBiz.list(activityId);
            List<NewsVo> list = activityVideoBiz.newsList(activityId);
            activityVo.setVideoNum((Integer) Optional.ofNullable(redisUtils.hget("activity_participate_news_count", String.valueOf(activityId))).orElse(0));
            Integer count = (Integer) Optional.ofNullable(redisUtils.hget("activity_participate_member_count", String.valueOf(activityId))).orElse(0);
            if (count == 0) {
                String activityMemberKey = MessageFormat.format(CacheKey.activity_member_record, activityId);
                count = new Long(redisUtils.sGetSetSize(activityMemberKey)).intValue();
            }
            activityVo.setJoinNum(count);
            List<String> headImgs = new ArrayList<String>();
            if (!ObjectUtils.isEmpty(list)) {
                Integer size = list.size() > 10 ? 10 : list.size();
                for (int i = 0; i < size; i++) {
                    MemberVo memberVo = memberBiz.info(list.get(i).getMemberId());
                    if (!ObjectUtils.isEmpty(memberVo)) {
                        headImgs.add(memberVo.getAvatarUrl());
                    }
                }
            }
            activityVo.setHeadImgs(headImgs);
        }
        return activityVo;
    }

    public ServiceResult participate(Integer flag, Integer memberId, Integer activityId) {
        Long nowSecond = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        ActivityVo activityVo = cacheBiz.activityInfoCache(activityId);
        if (!ObjectUtils.isEmpty(activityVo) && activityVo.getEndTime() >= nowSecond) {
            if (flag == 1) {
                save(memberId, activityId);
            } else {
                cancel(memberId, activityId);
            }
        }
        //return buildOK(true, flag == 1?"参与成功":"取消成功");
        return buildOK(true, flag == 1 ? "" : "");

    }

    public void save(Integer memberId, Integer activityId) {
        String memberActivityKey = MessageFormat.format(CacheKey.member_activity_record, memberId);
        String activityMemberKey = MessageFormat.format(CacheKey.activity_member_record, activityId);
        redisUtils.sSet(memberActivityKey, activityId);
        redisUtils.sSet(activityMemberKey, memberId);
    }

    public void cancel(Integer memberId, Integer activityId) {
        String memberActivityKey = MessageFormat.format(CacheKey.member_activity_record, memberId);
        String activityMemberKey = MessageFormat.format(CacheKey.activity_member_record, activityId);
        redisUtils.setRemove(memberActivityKey, activityId);
        redisUtils.setRemove(activityMemberKey, memberId);
    }

    public JsonObject query(String token, Integer activityId) {
        String memberKey = MessageFormat.format(CacheKey.memberToken, token);
        Object memberId = redisUtils.get(memberKey);
        JsonObject result = new JsonObject();
        String activityMemberKey = MessageFormat.format(CacheKey.activity_member_record, activityId);
        if (ObjectUtils.isEmpty(memberId)) {
            result.addProperty("status", false);
            result.addProperty("newsInfo", "0");
        } else {
            boolean flag = redisUtils.sHasKey(activityMemberKey, memberId);
            if (flag) {
                List<Integer> newsIds = new ActivityNews().selectList(new QueryWrapper<ActivityNews>().eq(ActivityNews.ACTIVITY_ID, activityId)).stream().map(ActivityNews::getNewsId).collect(Collectors.toList());
                if (!newsIds.isEmpty()) {
                    newsIds = new News().selectList(new QueryWrapper<News>()
                            .eq(News.MEMBER_ID, memberId)
                            .eq(News.VIDEO_SOURCE, 1)
                            .eq(News.DELETED, 1)
                            .in(News.NEWSID, newsIds)
                            .orderByDesc(News.CTIME)
                    ).stream().map(News::getNewsId).collect(Collectors.toList());
                }
                if (!newsIds.isEmpty()) {
                    String newsKey = MessageFormat.format(CacheName.getNewsInfo, String.valueOf(newsIds.get(0)));
                    NewsVo exsitNewsVo = (NewsVo) redisUtils.get(newsKey);
                    if (exsitNewsVo == null) {
                        exsitNewsVo = newsService.getById(newsIds.get(0));
                    }
                    if (exsitNewsVo == null || exsitNewsVo.getState().equals(0) || exsitNewsVo.getState().equals(5)) {
                        result.addProperty("newsInfo", "0");
                    } else if (exsitNewsVo.getState().equals(1)) {
                        result.addProperty("newsInfo", "1");
                    } else {
                        result.addProperty("newsInfo", "2");
                    }
                } else {
                    result.addProperty("newsInfo", "0");
                }
            } else {
                result.addProperty("newsInfo", "0");
            }
            result.addProperty("status", flag);
        }

        Integer count = (Integer) Optional.ofNullable(redisUtils.hget("activity_participate_member_count", String.valueOf(activityId))).orElse(0);
        if (count == 0) {
            count = new Long(redisUtils.sGetSetSize(activityMemberKey)).intValue();
        }
        result.addProperty("count", count);
        return result;
    }

    public List<ActivityVo> list(Integer memberId) {
        String memberActivityKey = MessageFormat.format(CacheKey.member_activity_record, memberId);
        Set<Object> set = redisUtils.sGet(memberActivityKey);
        List<ActivityVo> list = new LinkedList<ActivityVo>();
        Long nowSecond = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        if (!ObjectUtils.isEmpty(set)) {
            set.forEach(s -> {
                ActivityVo activityVo = cacheBiz.activityInfoCache(Integer.valueOf(s.toString()));
                if (!ObjectUtils.isEmpty(activityVo) && activityVo.getEndTime() >= nowSecond && 1 == activityVo.getState()) {
                    list.add(activityVo);
                } else {
                    redisUtils.setRemove(memberActivityKey, s);
                }
            });
        }
        return list;
    }

    public ServiceResult jumpPath(Integer memberId, String jumpPath) {
        MemberVo memberVo = memberBiz.info(memberId);
        StringBuffer sb = new StringBuffer(jumpPath);
        if (!ObjectUtils.isEmpty(memberVo) && !ObjectUtils.isEmpty(jumpPath)) {
            String secret = cacheBiz.getSystemDict(Constants.activity_jump_secret);
            JsonObject u = new JsonObject();
            u.addProperty("c", "WNAPP");
            u.addProperty("t", System.currentTimeMillis());
            u.addProperty("userId", memberVo.getMemberId());
            u.addProperty("nickName", memberVo.getNickName());
            u.addProperty("phone", memberVo.getPhone());
            u.addProperty("regTime", memberVo.getRegTime().getTime());
            u.addProperty("bindCa", memberVo.getBindCa());
            u.addProperty("smartCardCode", memberVo.getSmartCardCode());
            try {
                String uString = ThreeDesUtils.encode3DesBase64(u.toString().getBytes(), secret);
                if (jumpPath.contains("?")) {
                    sb.append("&u=");
                } else {
                    sb.append("?u=");
                }
                sb.append(URLEncoder.encode(uString, "UTF-8"));
                jumpPath = sb.toString();
            } catch (Exception e) {
                log.error("[活动跳转获取用户信息失败]:{}", e);
            }

        }
        return buildOK(jumpPath);
    }

//    public static void main(String[] args) throws UnsupportedEncodingException {
////    	https://catv-test.chinaotttv.com/h5/file?u=
//    	String a = URLEncoder.encode("Kt5OQNl/en/hULaFKu2hq/wJuAjDmZM+kX3q0/imlBI2PGc9FH5b+JUwBYWr5/0VKegChICZHTRG8mNFWuqhINOWrIUKilQHTug8flX7QKtlXVPNsqngZhFyfzOxIXju79p+c+px/mooJg0Pdr4WmSGIl3mZoMiV2rODUjFqZFu4b8wLhEOMPPEf2uhkjZ9c6BUkubySDxk7HsgLJgvY8g==","UTF-8");
//	}
}
